package net.qqxh.common.utils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class FileAnalysisTool {
    public static String getFileFix(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    /**
     * 源文件和视图文件异地存储
     *
     * @param path
     * @param viewFix
     * @return
     */
    public static String getOffSiteViewDir(String srcDir,String viewDir, String path, String viewFix) {
        if (StringUtils.isEmpty(viewFix)) {
            return path;
        }
        File source = new File(srcDir);
        File view = new File(viewDir);
        String p = replaceFirst(path, source.getPath(), view.getPath());
        return p + "." + viewFix;
    }
    public static String getFileSourceByView(String srcDir,String viewDir,String path){
        File source = new File(srcDir);
        File view = new File(viewDir);
        String p = replaceFirst(path, view.getPath(), source.getPath());
        return p.substring(0,p.lastIndexOf("."));
    }
    /**
     * 字符串替换，左边第一个。
     *
     * @param str    源字符串
     * @param oldStr 目标字符串
     * @param newStr 替换字符串
     * @return 替换后的字符串
     */
     public static String replaceFirst(String str, String oldStr, String newStr) {
        if(!newStr.endsWith(File.separator)){
            newStr+=File.separator;
        }
        if(!oldStr.endsWith(File.separator)){
            oldStr+=File.separator;
        }
        int i = str.indexOf(oldStr);
        if (i == -1) {
            return str;
        }
        {
            str = str.substring(0, i) + newStr + str.substring(i + oldStr.length());
        }
        return str;
    }
    /**
     * 将字符串中的中文进行编码
     * @param s
     * @return 返回字符串中汉字编码后的字符串
     */
    public static String genIdByPath(String s ){
        char[] ch = s.toCharArray();
        String result = "";
        for(int i=0;i<ch.length;i++){
            char temp = ch[i];
            if(isChinese(temp)){
                try {
                    String encode = URLEncoder.encode(String.valueOf(temp), "utf-8");
                    result = result + encode;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }else{
                result = result+temp;
            }
        }
        return result;
    }
    /**
     * 判断字符是否为汉字
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;
    }


    public static void main(String[] args) {
        System.out.print(genIdByPath("d://你好哈哈哈/哈哈/ddd"));
    }
}
